package com.kevin.proxy;

import com.kevin.constant.ReqType;
import com.kevin.constant.RpcConstant;
import com.kevin.constant.SerialType;
import com.kevin.core.*;
import com.kevin.protocol.NettyClient;
import io.netty.channel.DefaultEventLoop;
import io.netty.util.concurrent.DefaultPromise;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class RpcInvocationHandler implements InvocationHandler {

    private String serviceIp;

    private int servicePort;

    public RpcInvocationHandler(String serviceIp, int servicePort) {
        this.serviceIp = serviceIp;
        this.servicePort = servicePort;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        RpcProtocol<RpcRequest> requestRpcProtocol =new RpcProtocol<>();
        System.out.println(1);
        //构建rpcRequest对象
        RpcRequest rpcRequest =new RpcRequest();
        System.out.println(2);
        rpcRequest.setClassName(method.getDeclaringClass().getName());
        rpcRequest.setMethodName(method.getName());
        rpcRequest.setParamTypes(method.getParameterTypes());
        rpcRequest.setParams(args);
        requestRpcProtocol.setContent(rpcRequest);
        System.out.println("requestRpcProtocol is :"+requestRpcProtocol.toString());
        //构建Header对象
        long requestId = RequestHolder.REQUEST_ID_MANAGER.getAndIncrement();
        Header header = new Header(
                RpcConstant.MAGIC,
                SerialType.SERIAL_JSON.getSerialType(),
                ReqType.REQ_REQUERST.getCode(),
                requestId,
                0);
        requestRpcProtocol.setHeader(header);

        NettyClient nettyClient = new NettyClient("127.0.0.1",8080);
        RpcFuture<RpcResponse> future=new RpcFuture<>(new DefaultPromise<RpcResponse>(new DefaultEventLoop()));
        RequestHolder.FUTURE_MAP.put(requestId,future);
        nettyClient.sendRequest(requestRpcProtocol);

        System.out.println("被代理了哦");


        return future.getPromise().get().getData();
    }
}
